package com.yang.sso.oauth.oauth.exception;

import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.enums.ResultCode;
import com.yang.sso.oauth.utils.jackson.JacksonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author lslands
 * @Version 1.0
 * @Date 2023/3/6 10:26
 * @PackageName:com.auth.boot.oauth2.exception
 * @ClassName: MyAuthenticationEntryPoint
 * @Description:    Oauth2 令牌端点异常
 */
@Component
public class MyAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if(e instanceof BadCredentialsException){
            //如果是client_id和client_secret相关异常 返回自定义的数据格式
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            Result result = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
            response.getWriter().write(JacksonUtil.bean2Json(result));
        }else if(e instanceof InsufficientAuthenticationException){
            //如果是没有携带token
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            Result result = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
            response.getWriter().write(JacksonUtil.bean2Json(result));
        }else {
            super.commence(request,response,e);
        }
    }
}
